import { reactive, onMounted, defineComponent, toRefs, getCurrentInstance } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import projectApi from '@/api/inwarehouse/project-api'
import tenantApi from '@/api/system/tenant-api'
import ZlrtTable from '@/components/zlrt-table/table.vue'
import ZlrtSearch from '@/components/zlrt-search/search.vue'
import TableContext from '@/components/zlrt-table/table-context'
import requirementApi from '@/api/purchase/requirement-api'
// import {useRouter} from 'vue-router'
export default defineComponent({
  components: {
    ZlrtTable,
    ZlrtSearch
  },
  setup() {
    const disabledOptions = [
      // { label: '正常', value: 0 },
      // { label: '停用', value: 1 },
      { label: '生产中', value: 2 },
      { label: '已完成', value: 3 },
      { label: '已发货', value: 4 }
    ]

    const ctx = reactive(new TableContext(getCurrentInstance(), {
      title: '项目',
      api: projectApi,
      columns: [
        // { prop: 'id', label: '序号' },
        { prop: 'name', label: '项目名称', valueType: 'slot'},
        { prop: 'originalNo', label: '合同号', valueType: 'input', width: 150 },
        { prop: 'productCompleteDate', label: '生产完成日期', slot: true, width: 150 },
        { prop: 'planCompleteDate', label: '计划发货日期', slot: true, width: 150 },
        { prop: 'disabled', label: '状态', slot: true, valueType: 'select', options: disabledOptions, permit: ['core:user:save'], width: 100 },
        { prop: 'operation', label: '操作', slot: true, width: 250 }
      ],
      // 表单校验项规则
      rules: {
        // tenantId: [{ required: true, message: '请选择租户', trigger: 'change' }],
        name: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
        originalNo: [{ required: true, message: '请输入合同号', trigger: 'blur' }],
        productCompleteDate: [{ required: true, message: '请选择生产完成日期', trigger: 'change' }],
        planCompleteDate: [{ required: true, message: '请选择计划发货日期', trigger: 'change' }],
        disabled: [{ required: true, message: '请选择状态', trigger: 'change' }]
      },
      other: {
        // 状态切换
        // statusChanged: (row) => {
        //   const { username, disabled } = row
        //   ElMessageBox.confirm(`确认要${disabled ? '停用' : '启用'}"${username}"${ctx.title}吗？`, '温馨提示', {
        //     confirmButtonText: '确定',
        //     cancelButtonText: '取消',
        //     type: 'warning',
        //     draggable: true
        //   })
        //     .then(async () => {
        //       const res = await projectApi.save(row)
        //       if (res.success) {
        //         ElMessage.success(`${disabled ? '停用' : '启用'}成功`)
        //       } else {
        //         row.disabled = !disabled
        //       }
        //     })
        //     .catch(() => {
        //       row.disabled = !disabled
        //     })
        // },
        getStatusname(val: number) {
          const obj = disabledOptions.find(item => {
            return item.value === val
          })
          if (obj) {
            return obj.label
          }
        },
        formatDate(str) {
          if(!str) {
            return '-'
          }
          return str.substring(0, 10)
        },
        async getInventoryDetail(row) {
          requirementCtx.data = [];
          if(requirementCtx.loading) {
            return
          }
          requirementCtx.loading = true;
          const id = row.id;
          const res = await requirementApi.clacRequire(id);
          requirementCtx.loading = false;
          if(res.success) {
            const arr = []
            const orderGoodsList = res.data.orderGoodsList;
            orderGoodsList.map(ogl => {
              const index = arr.findIndex(ar => {
                return ogl.barCode === ar.barCode && ogl.skuName === ar.skuName;
              })
              if(index === -1) {
                arr.push(ogl)
              } else {
                arr[index].number = (arr[index].number * 1000 + ogl.number * 1000) / 1000
              }
            })
            requirementCtx.data = arr;
            requirementCtx.dialogVisible = true;
          }
        },
        async upload(options) {
          if(!options) {
            return
          }
          data.importLoading = true;
          const res = await projectApi.upload({ file: options.file });
          data.importLoading = false;
          if(res.success) {
            ElMessage.success('导入排产计划成功');
          }
        }
      }
    }))

    const requirementCtx = reactive({
      loading: false,
      dialogVisible: false,
      columns: [
        // { prop: 'id', label: '序号' },
        { prop: 'skuName', label: '物料名称' },
        { prop: 'barCode', label: '物料编码' },
        { prop: 'specification', label: '规格型号' },
        // { prop: 'locationName', label: '库位名称' },
        // { prop: 'locationCode', label: '库位编码' },
        { prop: 'number', label: '需求数量', width: '150' },
        { prop: 'inventoryList', label: '入库数量', width: '150', slot: true },
        { prop: 'isCheck', label: '缺货提醒', slot: true, width: '150' },
        { prop: 'numberCheck', label: '提醒数量', slot: true, width: '150' },
        { prop: 'unit', label: '单位', width: '100' }
      ],
      data: [],
      other: {
        getInventoryNum(list) {
          if(!list || list.length === 0) {
            return 0
          }
          let num = 0;
          list.map(li => {
            num = (num * 1000 + li.number * 1000) / 1000
          })
          return num
        },
        async changeCheck(row) {
          const { projectId, barCode, isCheck, skuName, numberCheck } = row
          ElMessageBox.confirm(`确认要${isCheck ? '开启' : '关闭'}"${skuName}"缺货提醒吗？`, '温馨提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            draggable: true
          })
            .then(async () => {
              const params = {
                projectId,
                oldBarCode: barCode,
                isCheck,
                skuName,
                numberCheck
              }
              const res = await projectApi.changeBarCode(params)
              if (res.success) {
                ElMessage.success(`${isCheck ? '开启' : '关闭'}成功`)
              } else {
                row.isCheck = !isCheck
              }
            })
            .catch(() => {
              row.isCheck = !isCheck
            })
        },
        async changeNumberCheck(row) {
          const { projectId, barCode, isCheck, skuName, numberCheck } = row
          const params = {
            projectId,
            oldBarCode: barCode,
            isCheck,
            skuName,
            numberCheck
          }
          const res = await projectApi.changeBarCode(params)
          if(res.success) {
            ElMessage.success('修改成功')
            // ctx.other.getInventoryDetail()
          }
        }
      }
    })

    const data = reactive({
      ctx,
      requirementCtx,
      disabledOptions,
      tenantOptions: [],
      importLoading: false,
      importFiles: []
    })


    const getTenant = async () => {
      const params = { filter: { disabled: false } }
      const res = await tenantApi.list(params)
      if (res.success) {
        data.tenantOptions = res.data?.records
      }
    }

    // init
    onMounted(() => {
      getTenant()
      ctx.loadData()
    })

    return {
      ...toRefs(data)
    }
  }
})
